﻿@model AddressControllerModel.Index
<div class="my-main">
    <div class="ui-box  ui-box-alpha">
        <div class="ui-box-head">
            <div class="ui-box-head-title">
                收货地址</div>
            <span class="ui-box-head-text"></span><a href="#" class="ui-box-head-more"></a>
        </div>
        <div class="ui-box-container">
            <div class="ui-box-content">
                <div class="ui-tiptext-container ui-tiptext-container-message">
                    <p class="ui-tiptext ui-tiptext-message">
                        <i class="ui-tiptext-icon iconfont" title="提示"></i> <span>最多添加 5 个收货地址，您还可以添加
                            @(5 - Model.Addresses.Count)
                            个收货地址。</span>
                    </p>
                </div>
            </div>
        </div>
        <div class="ui-box-container-noborder">
            <div class="address-list">
                @Model.Addresses.Each(@<div id="address-@item.Item.Id" class="address-list-item @(item.Index == 4 ? "address-list-item-last" : string.Empty) @(item.Item.IsDefault ? "address-list-item-default" : string.Empty)" >
                    <div class="row">
                        <div class="col-md-8">
                            <div class="address-list-item-content">
                                <p>
                                    <strong title="@(item.Item.Name)">@(item.Item.Name)</strong> <span>(@(item.Item.Mobile)
                                        @(item.Item.Phone))</span>
                                </p>
                                <p>@(item.Item.Province)
                                    @(item.Item.City)
                                    @(item.Item.District)
                                    @item.Item.Address (@item.Item.PostalCode)</p>
                            </div>
                        </div>
                        <div class="col-md-2 address-list-item-actions">
                            @if (item.Item.IsDefault)
                            {
                                <span>默认地址</span>
                            }
                            else
                            {
                                <a id="address-@(item.Item.Id)-setdefault" style="display: none;" onclick="setDefaultAddress(@item.Item.Id)" href="javascript:void(0);" title="设为默认">
                                    设为默认</a>
                            }
                        </div>
                        <div class="col-md-2 address-list-item-actions">
                            <a title="修改" href="javascript:void(0);" onclick="editAddress(@item.Item.Id)"><i
                                class="icon-pencil"></i>修 改</a> <a data-trigger="confirm" data-id="@(item.Item.Id)" data-content="<p id='address-delete-confirm'>确定删除该地址？</p>" href="javascript:void(0);" data-action="removeAddress">
                                    <i class="icon-remove "></i>删 除</a>
                        </div>
                    </div>
                </div>)
                @if (Model.Addresses.Count < 5)
                {
                    <div class="address-list-item-extra">
                        <a class="button button-follow" title="添加收货地址" href="javascript:void(0);" onclick="addAddress();">
                            <span class="button-left">&nbsp;</span> <span class="button-text">添加收货地址</span><span
                                class="button-right">&nbsp;</span></a>
                    </div>
                }
            </div>
        </div>
    </div>
</div>
@section js{
    @Url.Ayatta().StaticJs("china.area")
    <script id="address-form-tmpl" type="text/x-jquery-tmpl">     
        <div class="address-form">
            <form id="form-address" class="form-horizontal" action="/address/address/<%=Id%>"   onsubmit="return submitAddress(this);">
            
                <div id="form-group-for-name" class="form-group">
                    <label class="col-md-2 control-label" for="name">
                        收货人</label>
                    <div class="col-md-4">                          
                        <input type="text" id="name" name="name" class="form-control" maxlength="8" placeholder="收货人姓名" value="<%=Name%>">                            
                    </div>
                    <div class="col-md-3">
                        <p id="help-block-for-name" class="help-block">
                            请输入收货人真实姓名！</p>
                    </div>
                </div>
                <div id="form-group-for-company" class="form-group">
                    <label  class="col-md-2 control-label" for="company">
                        公司名称</label>
                    <div class="col-md-4">                         
                        <input type="text" id="company" name="company" class="form-control" maxlength="20" placeholder="公司名" value="<%=Company%>">                         
                    </div>
                    <div class="col-md-3">
                        <p id="help-block-for-company" class="help-block">
                            请输入公司名称（可不填）！</p>
                    </div>
                </div>
                <div id="form-group-for-areaId" class="form-group">
                    <label class="col-md-2 control-label" for="areaId">
                        所在地区</label>
                    <div class="col-md-6">
                        <select id="province" class="input-medium" onchange = "areaChange(this)">
                            <option value=''>请选择</option>
                            <%_.each(Provinces,function(o){%>
                            <option value="<%=o.Id%>" <%=(o.Selected?"selected='selected'":"")%>><%=o.Name%></option>
                            <%});%>
                        </select><select  id="city" class="input-medium" onchange = "areaChange(this)">
                                     <option value=''>请选择</option>
                                     <%_.each(Cities,function(o){%>
                                     <option value="<%=o.Id%>" <%=(o.Selected?"selected='selected'":"")%>><%=o.Name%></option>
                                     <%});%>
                                 </select><select  id="district" name="areaId" class="input-medium" onchange = "areaChange(this)">
                                              <option value=''>请选择</option>
                                              <%_.each(Districts,function(o){%>
                                              <option value="<%=o.Id%>" <%=(o.Selected?"selected='selected'":"")%>><%=o.Name%></option>
                                              <%});%>
                                          </select>                                           
                    </div>
                    <div class="col-md-4">
                        <p id="help-block-for-areaId" class="help-block">
                        </p>
                    </div>
                </div>
                <div id="form-group-for-address" class="form-group">
                    <label class="col-md-2 control-label" for="address">
                        街道地址</label>
                    <div class="col-md-4">                              
                        <input type="text" id="address" name="address" class="form-control" maxlength="20" placeholder="详细地址" value="<%=Address%>">                     
                          
                    </div>
                    <div class="col-md-3">
                        <p id="help-block-for-address" class="help-block">
                            不需要重复填写省/市/区！</p>
                    </div>
                </div>
                <div id="form-group-for-postalCode" class="form-group">
                    <label class="col-md-2 control-label" for="postalCode">
                        邮政编码</label>
                    <div class="col-md-4">
                        <input type="text" id="postalCode" name="postalCode" class="form-control" maxlength="6" placeholder="邮政编码"
                               value="<%=PostalCode%>">
                    </div>
                    <div class="col-md-3">
                        <p id="help-block-for-postalCode" class="help-block">
                            请输入邮政编码！</p>
                    </div>
                </div>
                <div id="form-group-for-contact" class="form-group">
                    <label class="col-md-2 control-label">
                        联系方式</label>
                    <div class="col-md-10">
                        <div class="row">
                            <div class="col-md-3">
                                <label for="mobile">
                                    移动电话</label>
                                <br/>
                                <input type="text" id="mobile" name="mobile" class="form-control input-small" maxlength="11" placeholder="移动电话"
                                       value="<%=Mobile%>">
                            </div>                       
                            <div class="col-md-3">
                                <label for="phone">
                                    固定电话</label>   <br/><input type="text" id="phone" name="phone" class="form-control input-medium" maxlength="18" placeholder="固定电话"
                                                               value="<%=Phone%>">
                            </div>
                            <div class="col-md-6">
                                <p id="help-block-for-contact" class="help-block">
                                    移动电话、固定电话必填一项！</p>
                            </div>
                        </div>
                    </div>                        
                </div>
                <div class="form-group">
                      
                    <div class="col-md-offset-2 col-md-8">                          
                        <%if(Id>0){%>
                        <button class="ui-btn ui-btn-alpha" type="submit">
                            确认修改</button>
                        <button type="button" class="ui-btn ui-btn-beta" onclick="cancleAddress(<%=Id%>);">
                            取消修改</button>
                        <%}else{%>
                       
            <button class="ui-btn ui-btn-alpha" type="submit">保 存</button>
            <button type="button" class="ui-btn ui-btn-beta" onclick="cancleAddress(0);">
                取 消</button>
            <%}%>
            <%if(IsDefault){%>
                        <input type="hidden" value="True" checked="checked" name="IsDefault"/>
            <%}%>
                        </div>
                    </div>
      
      
        </form>
    </div>
    </script>
    <script type="text/javascript">
        var addresses = @(Html.Raw(Model.JsonData)) ;
         function editAddress(id) {
            if (id > 0) {
                var address =_.findWhere(addresses, { Id: id });// $.Enumerable.From(addresses).Where(function(o) { return o.Id == id; }).FirstOrDefault();
                var template = _.template($('#address-form-tmpl').html());
                var provinceId = address.AreaId.substr(0, 2);
                var cityId = address.AreaId.substr(0, 4);
                var provinces = [];
                var temp=_.where(ChinaAreas, { ParentId: '0' });
                _.each(temp, function(o) {
                    var selected = false;
                    if(provinceId==o.Id) {
                         selected = true;
                    }
                    var province = { Id:o.Id,Name:o.Name,Selected:selected};
                    provinces.push(province);
                });
                address.Provinces =provinces;
                
                 var cities = [];
                temp=_.where(ChinaAreas, { ParentId: provinceId });
                _.each(temp, function(o) {
                    var selected = false;
                    if(cityId==o.Id) {
                         selected = true;
                    }
                    var city = { Id:o.Id,Name:o.Name,Selected:selected};
                    cities.push(city);
                });
                address.Cities = cities;
                
                var districts = [];
                temp=_.where(ChinaAreas, { ParentId: cityId });
                _.each(temp, function(o) {
                    var selected = false;
                    if(address.AreaId==o.Id) {
                         selected = true;
                    }
                    var district = { Id:o.Id,Name:o.Name,Selected:selected};
                    districts.push(district);
                });
                address.Districts = districts;
                
                var html = template(address);
                
                $('.address-form').remove();
                $("#address-" + id).hide(); 
                $('.address-list-item').not("#address-" + id).show();
                $("#address-" + id).after(html);
                if (addresses.length < 5) {
                    $('.address-list-item-extra').show();
                }
                $('select').select2();
                $("#form-address").submit();
            }
        }
        function addAddress() {
            var isDefault = addresses.length ==0;
            var address = { Id: 0, Name: '',Company:'', Address: '', PostalCode: '', Phone: '', Mobile: '', IsDefault: isDefault };
           var provinces = [];
                var temp=_.where(ChinaAreas, { ParentId: '0' });
                _.each(temp, function(o) {
                    var selected = false;
                    var province = { Id:o.Id,Name:o.Name,Selected:selected};
                    provinces.push(province);
                });
                address.Provinces =provinces;
             address.Cities = [];
            address.Districts = [];
            address.Districts = [];
            var template = _.template($('#address-form-tmpl').html());
            var html = template(address);

            $('.address-form').remove();
            $('.address-list-item').show();
            $(".address-list-item-extra").hide().after(html);
             $('select').select2();
            $("#form-address").submit();
        }
        
        function removeAddress() {
            var self = this;
            var id = self.options.id||0;
            if(id<1) {
                $('#address-delete-confirm').html('删除地址失败！');
                return;
            }
            else {
                $.postJSON('/address/delete', { param: id }, function(result) {
                    if (result.Status == true) {
                        self.close();
                        window.location.reload();
                    } else {
                        $('#address-delete-confirm').html('删除地址失败！');
                        return;
                    }
                });
            }
        }
        function setDefaultAddress(id) {
             $.postJSON('/address/setdefault', { param: id }, function(result) {
                 if (result.Status == true) {
                                window.location.reload();
                            }else {
                     alert(result.Message);
                 }
            });
        }
        function cancleAddress(id) {
            if(id>0) {
                $('.address-form').remove();
                $('#address-' + id).show();
            } else {
                $(".address-form").remove();
                $('.address-list-item-extra').show();
            }
        }
        function areaChange(obj) {
            var val = $(obj).val();
            if (val.length == 6) {
                var area = _.findWhere(ChinaAreas, { Id: val });
                $("#postalCode").val(area.Zip);
                return;
            }
            $("#postalCode").val('');
              var html = [];
            var areas = _.where(ChinaAreas, { ParentId: val });
            html.push("<option value=''>请选择</option>");
            _.each(areas, function(o) {
                html.push("<option value=" + o.Id + ">" + o.Name + "</option>");
            });
            
            if (val.length == 4) {
                $("#district").html(html.join(""));
            }
            if (val.length == 2) {
                $("#district").html("<option value=''>请选择</option>");
                $("#city").html(html.join(""));
            }
            $('select').select2();
        }

        function submitAddress(form) {
            $(form).validate({
                rules: {
                    name: { required: true },
                    areaId: { required: true },
                    address: { required: true },
                    postalCode: { required: true, postcode: true }
                },
                messages: { name: { required: '请填写真实有效的姓名！' },areaId:{required: '请选择所在地区！'}, address: { required: '请填写真实有效的街道地址信息！' }, postalCode: { required: '请填写邮政编码！', postcode: '请填写正确的邮政编码！' } },
                submitHandler: function(f) {
                    var isMobile = (document.getElementById('mobile').value.isMobile());
                    var isPhone = (document.getElementById('phone').value.isPhone());
                    if (isMobile || isPhone) {
                        var param = $(f).serialize();
                        $.postJSON(form.action, param, function(result) {
                            if (result.Status == true) {
                                window.location.reload();
                            }
                            else {
                                alert(result.Message);
                            }
                        });
                    } else {
                        var error = $("<span class='invalid'>移动电话、固定电话必填一项！</span>");
                        $("#help-block-for-contact").html(error);
                         setTimeout(function () {
                                $("#help-block-for-contact").html('&nbsp;');
                            }, 2000);
                    }
                },
               
                errorClass: "invalid",
                errorElement: "span",
                errorPlacement: function (error, element) {
                    var id = $(element).attr('id');
                    $("#help-block-for-" + id).html(error);
                },
                highlight: function (element, errorClass, validClass) {
                    var id = element.id;
                    $(element).removeClass(validClass).addClass(errorClass);
                    //$("#form-group-for-" + id).removeClass('has-success').addClass('has-error');
                },
                unhighlight: function (element, errorClass, validClass) {
                    var id = element.id;
                    $(element).removeClass(errorClass).addClass(validClass);
                    $("#help-block-for-" + id).html('&nbsp;');
                    //$("#form-group-for-" + id).removeClass('has-error').addClass('has-success');
                }
            });
            return false;
        }

        $(function() {
            $('.address-list-item').hover(function(e) {
                if(!$(this).hasClass('address-list-item-default')) {
                    var id = e.target.id;
                    var targetId = id + "-setdefault";
                    $('#' + targetId).show();
                }
            }, function(e) {
             if(!$(this).hasClass('address-list-item-default')) {
                    var id = e.target.id;
                    var targetId = id + "-setdefault";
                    $('#' + targetId).hide();
                }
            });
        });
    </script>
}
